package cn.lg.soar.system.auth.controller;

import cn.lg.soar.common.model.HttpResult;
import cn.lg.soar.common.model.OneToManyDTO;
import cn.lg.soar.common.model.PageQuery;
import cn.lg.soar.common.model.PageResult;
import cn.lg.soar.core.annotations.IdempotentByParam;
import cn.lg.soar.core.annotations.constraints.Id;
import cn.lg.soar.database.base.controller.BaseController;
import cn.lg.soar.database.query.QueryParams;
import cn.lg.soar.database.query.SqueryWapper;
import cn.lg.soar.database.util.MpSqlUtils;
import cn.lg.soar.database.util.PageUtils;
import cn.lg.soar.mvc.annotations.*;
import cn.lg.soar.system.api.constant.ModuleConst;
import cn.lg.soar.system.auth.entity.DataScope;
import cn.lg.soar.system.auth.entity.Role;
import cn.lg.soar.system.auth.model.RoleDataScopeVO;
import cn.lg.soar.system.auth.model.RoleDto;
import cn.lg.soar.system.auth.service.IDataScopeService;
import cn.lg.soar.system.auth.service.IRoleService;
import cn.lg.soar.system.auth.service.RoleMenuService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.Serializable;
import java.util.List;

/**
 * @author luguoxiang
 * 开源项目：https://gitee.com/lgx1992/lg-soar 求star！请给我star！请帮我点个star！
 */
@Validated
@Api(tags = "角色管理")
@RestController
@RequestMapping(ModuleConst.MODULE_NAME + "/role")
public class RoleController extends BaseController<Role, IRoleService> {

    @Override
    protected Serializable getId(Role entity) {
        return entity.getId();
    }

    @Autowired
    private RoleMenuService roleMenuService;
    @Autowired
    private IDataScopeService dataScopeService;

    private final static String SUBJECT = "角色";

    @Log(value = "新增" + SUBJECT, data = "#p0", dataId = "#$r.data")
    @IdempotentByParam("#p0")
    @CreateMapping
    public HttpResult<Serializable> create(@RequestBody @Validated RoleDto data) {
        return HttpResult.<Serializable>success("创建角色成功")
                .setData(this.service.create(data));
    }

    @Log(value = "修改" + SUBJECT, data = "#p0", dataId = "#p0.id")
    @UpdateMapping
    public HttpResult<Void> update(@RequestBody @Validated Role data) {
        return updateResult(data);
    }

    @Log(value = "删除" + SUBJECT, data = "#p0", type = Log.Type.TEXT)
    @RemoveMapping
    public HttpResult<Void> remove(@RequestBody List<Long> ids) {
        return super.removeResult(ids);
    }

    @DetailMapping
    public HttpResult<Role> detail(@Id Long id) {
        return detailResult(id);
    }

    @QueryMapping
    public HttpResult<PageResult<Role>> query(PageQuery pageQuery, QueryParams params, Long[] userIds, Long[] menuIds, Long[] orgIds){
        QueryWrapper<Role> wrapper = new SqueryWapper<>(Role.class).listWrapper(params);
        MpSqlUtils.handleInOrEq(userIds, (sql, value) -> {
            wrapper.exists("select * from lg_sys_user_2_role u where lg_sys_role.id=u.role_id and u.user_id " + sql, value);
        });
        MpSqlUtils.handleInOrEq(menuIds, (sql, value) -> {
            wrapper.exists("select * from lg_sys_role_2_menu m where lg_sys_role.id=m.role_id and m.menu_id " + sql, value);
        });
        MpSqlUtils.handleInOrEq(orgIds, (sql, value) -> {
            wrapper.exists("select * from lg_sys_org_2_role o where lg_sys_role.id=o.role_id and o.org_id " + sql, value);
        });
        IPage<Role> page = service.page(PageUtils.toPage(pageQuery), wrapper);
        return HttpResult.data(PageUtils.toPageResult(page));
    }

    @ListMapping
    public HttpResult<List<Role>> list(QueryParams params){
        return HttpResult.data(
                super.getList(params)
        );
    }

    @ExistMapping
    public HttpResult<Boolean> exist(QueryParams params){
        return super.existResult(params);
    }

    @Log(value = "导出" + SUBJECT, data = "#p0")
    @ExportMapping
    public void exports(String filename, QueryParams params, HttpServletResponse resp){
        super.exportExcel(filename, params, resp);
    }

    @Log(value = "导入" + SUBJECT)
    @ImportMapping
    public HttpResult<Void> imports(HttpServletRequest req){
        return super.importExcel(req);
    }

    @ApiOperation("清空缓存")
    @PostMapping(value = "clear-cache", name = "清空缓存")
    public HttpResult<Void> clearCache(){
        this.service.clearCache();
        return HttpResult.success();
    }

    @ApiOperation("设置角色菜单")
    @PostMapping(value = "set-menu-ids")
    public HttpResult<Void> setMenuIds(@RequestBody OneToManyDTO<Long, Long> dto){
        roleMenuService.setRoleMenu(dto.getMainId(), dto.getJoinIds());
        return HttpResult.success();
    }

    @ApiOperation("获取角色菜单id")
    @GetMapping(value = "get-menu-ids")
    public HttpResult<List<Long>> getMenuIds(@RequestParam Long roleId){
        List<Long> ids = roleMenuService.getMenuIds(roleId);
        return HttpResult.data(ids);
    }

    @ApiOperation("设置角色数据权限")
    @PostMapping(value = "set-data-scope")
    public HttpResult<Void> setDataScope(@RequestBody RoleDataScopeVO vo){
        dataScopeService.setRuleDataScope(vo);
        return HttpResult.success();
    }

    @ApiOperation("获取角色数据权限")
    @GetMapping(value = "get-data-scope")
    public HttpResult<List<DataScope>> getDataScope(@RequestParam Long roleId){
        List<DataScope> dataScopes = dataScopeService.getRuleDataScope(roleId);
        return HttpResult.data(dataScopes);
    }

}
